<template>
  <el-dialog :title="$t('basic.' + title)" :visible.sync="dialogFormVisible" custom-class="jtyj-dialog"
    :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-position="top">
      <el-form-item :label="$t('basic.name')" prop="scenarioName">
        <el-input v-model="form.scenarioName" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>

      <el-form-item :label="$t('basic.describe')" prop="scenarioDescription">
        <el-input v-model="form.scenarioDescription" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('basic.parentFolder')">
        <treeselect v-model="form.parentId" :options="treeData" :normalizer="normalizer" class="jtyj-input">
        </treeselect>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="jtyj-btn-cancel" @click="cancel">{{
        $t("setup.buttonText.cancel")
      }}</el-button>
      <el-button class="jtyj-btn-primary" @click="submitForm">{{
        $t("setup.buttonText.save")
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { 
  addScenario, 
  updateScenario
} from "@/api/myspace/scenario-edit-tool/scenario-edit";
import { mapState } from "vuex";
export default {
  data() {
    return {
      title: "newFolder",
      flag: "", // 新增文件夹的标志，判断是哪个部分的新增
      dialogFormVisible: false,
      form: {
        scenarioName: null,
        scenarioDescription: null,
        parentId: 0,
        userId: null,
        nodeType: 0,
      },
      treeData: [],
      rules: {
        scenarioName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        scenarioDescription: [{ required: true, message: "请输入描述", trigger: "blur" }],
      },
      normalizer(node) {
        // 返回映射后的键
        return {
          id: node.id,
          label: node.name,
          children: node.children?.length ? node.children : undefined,
        }
      },
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.id,
    }),
  },
  mounted() {
  },
  methods: {
    init(sign, node, treeData) {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['form'].resetFields();
        this.normalizerTreeData(treeData)
        if (sign == "add") {
          this.title = "newFolder";
          this.form.parentId = node ? node.id : 0
        } else {
          this.title = "editFolder";
          this.form.scenarioId = node.id;
          this.form.parentId = node.parentId;
          this.form.scenarioName = node.data.scenarioName;
          this.form.scenarioDescription = node.data.scenarioDescription;
        }
      });
    },

    /**
     * 标准化treeData, 为树添加根目录
     * @param treeData 
     */
    normalizerTreeData(treeData) {
      let rootFolder = {
        id: 0,
        name: "根目录",
        children: [],
        parentId: -1,
        type: 0
      }
      rootFolder.children = treeData
      this.treeData = this.filterFolders([rootFolder])
    },

    /**
     * 过滤出文件夹节点
     * @param nodes 
     */
    filterFolders(nodes) {
      return nodes
        .filter(node => node.type == 0) // 只保留文件夹节点
        .map(node => ({
          ...node,
          children: node.children ? this.filterFolders(node.children) : [], // 递归处理子节点
        }));
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    // 表单提交
    submitForm() {
      this.form.userId = this.userId;
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        if (this.form.scenarioId == null) {
          addScenario(this.form).then((response) => {
            if (response.code == 200) {
              this.$message.success(
                this.$toolHandle.getI18nName(
                  this.$zh.setup.responseText,
                  this.$en.setup.responseText,
                  this.$i18n.locale,
                  "success"
                )
              );
              this.$emit("refresh", response.data);
              this.dialogFormVisible = false;
            }
          });
        } else {
          updateScenario(this.form).then((response) => {
            if (response.code == 200) {
              this.$message.success(
                this.$toolHandle.getI18nName(
                  this.$zh.setup.responseText,
                  this.$en.setup.responseText,
                  this.$i18n.locale,
                  "success"
                )
              );
              this.$emit("refresh");
              this.dialogFormVisible = false;
            }
          });
        }
      });
    },
  },
};
</script>

<style></style>